﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ScrumDashboard.Library.Data;

namespace ScrumDashboard.Library.Models
{
    public class SprintViewData
    {
        public static readonly SprintViewData Empty = new SprintViewData() { Sprint = new Sprint(), ProductBacklog = new List<ProductBacklogItem>() };
        public Sprint Sprint { get; set; }
        public TeamSprint TeamSprint { get; set; }
        public IList<ProductBacklogItem> ProductBacklog { get; set; }


        public static SprintViewData Create(IRepository repo, string tfsProject, int sprint, int? teamSprint)
        {
            IProductBacklogItemHandler _pbHandler = repo.GetHandler<IProductBacklogItemHandler>();
            ISprintHandler _sprintHandler = repo.GetHandler<ISprintHandler>();
            ITeamSprintHandler _teamSprintHandler = repo.GetHandler<ITeamSprintHandler>();
            IBacklogItemHandler _backlogHandler = repo.GetHandler<IBacklogItemHandler>();


            SprintViewData view = new SprintViewData();
            view.Sprint = _sprintHandler.GetSprint(sprint);
            if (teamSprint.HasValue)
            {
                view.TeamSprint = _teamSprintHandler.GetTeamSprint(teamSprint.Value);
            }
            view.ProductBacklog = _pbHandler.GetProductBacklogs(tfsProject, view.TeamSprint == null ? view.Sprint.IterationPath : view.TeamSprint.IterationPath).ToList();

            IList<BacklogItem> backlogItems = _backlogHandler.GetBacklogItems(tfsProject, view.TeamSprint == null ? view.Sprint.IterationPath : view.TeamSprint.IterationPath);

            var sprintBacklog = from s in backlogItems where s.BacklogType == BacklogItemType.SprintBacklogTask select (SprintBacklogTask)s;
            var impediments = from s in backlogItems where s.BacklogType == BacklogItemType.Impediment select (Impediment)s;
            var acceptanceTests = from s in backlogItems where s.BacklogType == BacklogItemType.AcceptanceTest select (AcceptanceTest)s;

            foreach (ProductBacklogItem pbi in view.ProductBacklog)
            {
                pbi.SprintBacklog = (from s in sprintBacklog where s.ProductBacklogId == pbi.Id select s).ToList();
                pbi.Impediments = (from s in impediments where s.ProductBacklogId == pbi.Id select s).ToList();
                pbi.AcceptanceTests = (from s in acceptanceTests where s.ProductBacklogId == pbi.Id select s).ToList();
            }

            view.ProductBacklog = view.ProductBacklog;

            return view;
        }
    }
}
